import organization from '../api/organization'

const module = 'organizations'

// initial state
const state = {
  list: {},
  allList: [],
  curNode: null,
  editNode: null,
  page: {
    number: 0,
    size: 5,
    totalElements: 0,
    totalPages: 0
  }
}

// getters
const getters = {}

// actions
const actions = {
  reLoad ({ dispatch, state }) {
    if (state.curNode) {
      dispatch('findByParentId', {
        page: state.page.number,
        parentId: state.curNode.id
      })
    } else {
      dispatch('getList', {
        page: state.page.number
      })
    }
  },
  getList ({ dispatch, commit, state }, params = {}) {
    const { url, page, ...others } = params
    if (state.curNode) {
      dispatch('findByParentId', {
        parentId: state.curNode.id,
        page,
        ...others
      })
      return
    }
    organization.getList({
      cb: result => {
        commit('setList', {
          list: result._embedded[module],
          page: result.page.number
        })
        commit('setPage', result.page)
      },
      ecb: error => {
        if (error && error.response && error.response.status === 304) {
          commit('setPageNum', page || 0)
        }
      },
      url: url || 'organizations/search/findByParentIdIsNull',
      params: {
        projection: 'OrganizationWithParent',
        sort: 'num',
        page,
        ...others
      }
    })
  },
  findByParentId ({ commit }, { parentId, page, ...others }) {
    organization.getList({
      cb: result => {
        commit('setList', {
          list: result._embedded[module],
          page: result.page.number,
          parentId
        })
        commit('setPage', result.page)
      },
      ecb: error => {
        if (error && error.response && error.response.status === 304) {
          commit('setPageNum', page || 0)
        }
      },
      url: 'organizations/search/findByParentId',
      params: {
        projection: 'OrganizationWithParent',
        sort: 'num',
        parentId,
        page,
        ...others
      }
    })
  },
  loadChildrenByParentId ({ commit }, { item, cb }) {
    organization.loadChildren({
      cb,
      ecb: error => {
        console.log(error)
      },
      self: item.value,
      params: {
        size: 1000
      }
    })
  },
  getAllList ({ commit }) {
    organization.getList({
      cb: result => {
        commit('setAllList', result._embedded[module])
      },
      ecb: error => {
        console.log(error)
      },
      url: 'organizations/search/findByParentIdIsNull',
      params: {
        projection: 'OrganizationWithChildrenCount',
        size: 1000,
        sort: 'num'
      }
    })
  },
  remove ({ dispatch }, params) {
    const { ecb, ...others } = params
    organization.remove({
      ...others,
      ecb: error => {
        ecb && ecb(error)
        // 通过单独获取一个节点并添加到结尾避免全部刷新
        dispatch('reLoad')
      }
    })
  },
  delete ({ dispatch }, selection) {
    let idList = []
    for (let i in selection) {
      idList.push(selection[i].id)
    }
    organization.delete({
      cb: result => {
        console.log(result)
        dispatch('reLoad')
      },
      ecb: error => {
        console.log(error)
      },
      idList
    })
  },
  create ({ state }, params) {
    const { formData, cb, ...others } = params
    if (state.curNode) {
      formData.parent = state.curNode._links.self.href
    }
    organization.create(
      {
        formData,
        cb: result => {
          if (state.curNode) {
            organization.changeParent({
              parent: this.$mytools.clearUrl(result._links.parent.href),
              parentSelf: state.curNode._links.self.href,
              cb,
              ...others
            })
          } else {
            cb && cb(result)
          }
        }
      },
      ...others
    )
  },
  update ({ commit, dispatch, state }, params) {
    const { formData, cb, ...others } = params
    organization.update({
      formData,
      cb: result => {
        if (formData.num === state.editNode.num) {
          const newList = state.list
          for (let i in newList) {
            if (newList[i].id === state.editNode.id) {
              newList[i].name = formData.name
              newList[i].address = formData.address
              newList[i].description = formData.description
              break
            }
          }
          commit('setList', newList)
        } else {
          dispatch('reLoad')
        }
        cb && cb(result)
      },
      ...others
    })
  },
  setCurNode ({ commit, state }, index) {
    if (typeof index === 'number') {
      let node
      if (state.curNode) {
        node = state.list[state.curNode.id][state.page.number][index]
      } else {
        node = state.list[state.page.number][index]
      }
      commit('setCurNode', node)
    } else if (typeof index === 'string') {
      if (state.curNode.id === index) {
        return
      }
      for (let i in state.list) {
        for (let j in state.list[i]) {
          if (state.list[i][j].id === index) {
            commit('setCurNode', state.list[i][j])
          }
        }
      }
    } else {
      if (!state.curNode) {
        return
      }
      commit('setCurNode', null)
    }
  },
  setEditNode ({ commit, state }, index) {
    let node
    if (state.curNode) {
      node = state.list[state.curNode.id][state.page.number][index]
    } else {
      node = state.list[state.page.number][index]
    }
    commit('setEditNode', node)
  }
}

// mutations
const mutations = {
  setList (state, { list, page, parentId }) {
    if (parentId) {
      if (!state.list[parentId]) {
        state.list[parentId] = []
      }
      state.list[parentId][page] = list
    } else {
      state.list[page] = list
    }
  },
  setAllList (state, allList) {
    state.allList = allList
  },
  setPage (state, page) {
    state.page = page
  },
  setPageNum (state, num) {
    state.page.number = num
  },
  setCurNode (state, curNode) {
    state.curNode = curNode
  },
  setEditNode (state, editNode) {
    state.editNode = editNode
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
